<template v-hasPermi="['health:reserve:edit']">
  <div class="app-container" v-hasPermi="['health:reserve:edit']">
    <h2 class="chart-title">医院和企业预约统计</h2>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="chart-container">
          <h3>企业预约数量统计</h3>
          <div ref="companyChart" class="chart"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="chart-container">
          <h3>医院预约数量统计</h3>
          <div ref="hospitalChart" class="chart"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { listReserve } from "@/api/health/reserve.js";
defineOptions({
  name: 'HealthDataShow'
})

// 医院ID映射配置
const hospitalMap = {
  "103": "兰州新区第一人民医院",
  "104": "兰州新区中川镇卫生院",
  "105": "兰州新区瑞玲雅苑社区卫生服务中心",
  "106": "兰州新区新安社区卫生服务中心",
  "107": "兰州新区栖霞社区卫生服务中心",
  "108": "兰州新区西岔中心卫生院",
  "109": "兰州新区西岔综合门诊部(实训医院)",
  "110": "兰州新区秦川中心卫生院",
  "111": "兰州新区上川镇卫生院",
  "112": "兰州新区火家湾社区卫生服务站"
}

// DOM引用
const hospitalChart = ref(null)
const companyChart = ref(null)

// ECharts实例
let hospitalEchart = null
let companyEchart = null

// 获取数据并初始化图表
const fetchDataAndInitCharts = async () => {
  try {
    const response = await listReserve()

    if (response.code === 200) {
      const data = response.rows
      const hospitalStats = {}
      const companyStats = {}

      // 统计医院和企业数量
      data.forEach(item => {
        // 统计医院
        const hospitalName = hospitalMap[item.reserveHospital] || `未知医院 (ID: ${item.reserveHospital})`
        hospitalStats[hospitalName] = (hospitalStats[hospitalName] || 0) + 1

        // 统计企业
        if (item.unitName) {
          companyStats[item.unitName] = (companyStats[item.unitName] || 0) + 1
        }
      })

      // 更新图表
      updateHospitalChart(hospitalStats)
      updateCompanyChart(companyStats)
    } else {
      console.error('获取数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取数据出错:', error)
  }
}

// 更新医院饼图 - 添加中心位置上移
const updateHospitalChart = (data) => {
  const hospitalData = Object.entries(data).map(([name, value]) => ({ name, value }))
  const option = {
    title: {
      text: '',
      left: 'center',
      top: 5
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      type: 'scroll',
      formatter: function (name) {
        return name.length > 10 ? name.substring(0, 8) + '...' : name;
      }
    },
    series: [
      {
        name: '预约数量',
        type: 'pie',
        radius: '55%',
        // 关键修改：向上调整饼图位置 (水平居中，垂直上移)
        center: ['50%', '15%'], // [水平位置, 垂直位置]
        data: hospitalData,
        // 优化标签位置
        label: {
          position: 'outer',
          alignTo: 'edge',
          edgeDistance: '5%',
          formatter: '{b}: {c} ({d}%)',
          lineHeight: 15
        },
        labelLine: {
          length: 10,
          length2: 5, // 缩短第二段引导线
          smooth: true,
          lineStyle: {
            width: 1
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14px',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  if (hospitalChart.value) {
    hospitalEchart = echarts.init(hospitalChart.value)
    hospitalEchart.setOption(option)
  }
}

// 更新企业饼图 - 添加中心位置上移
const updateCompanyChart = (data) => {
  const companyData = Object.entries(data).map(([name, value]) => ({ name, value }))
  const option = {
    title: {
      text: '',
      left: 'center',
      top: 5
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      type: 'scroll',
      formatter: function (name) {
        return name.length > 10 ? name.substring(0, 8) + '...' : name;
      }
    },
    series: [
      {
        name: '预约数量',
        type: 'pie',
        radius: '55%',
        // 关键修改：向上调整饼图位置 (水平居中，垂直上移)
        center: ['30%', '15%'], // [水平位置, 垂直位置]
        data: companyData,
        // 优化标签位置
        label: {
          position: 'outer',
          alignTo: 'edge',
          edgeDistance: '5%',
          formatter: '{b}: {c} ({d}%)',
          lineHeight: 15
        },
        labelLine: {
          length: 10,
          length2: 5, // 缩短第二段引导线
          smooth: true,
          lineStyle: {
            width: 1
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14px',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  if (companyChart.value) {
    companyEchart = echarts.init(companyChart.value)
    companyEchart.setOption(option)
  }
}

// 调整图表大小
const resizeCharts = () => {
  hospitalEchart?.resize()
  companyEchart?.resize()
}

// 生命周期钩子
onMounted(() => {
  // 确保DOM加载完成后再初始化
  setTimeout(fetchDataAndInitCharts, 100)
  window.addEventListener('resize', resizeCharts)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
  hospitalEchart?.dispose()
  companyEchart?.dispose()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  border-radius: 8px;
}

.chart-title {
  text-align: center;
  margin-bottom: 25px;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  padding-bottom: 15px;
}

.chart-container {
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.chart-container:hover {
  transform: translateY(-3px);
}

.chart-container h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #606266;
  font-size: 16px;
}

.chart {
  height: 600px;
  min-height: 500px;
}
</style>